/**
 * xdiv 单页应用框架
 */
var pageCache = {};
var pageNameArray = new Array();
/**
 * 属性选择 , 不限标签
 */
$(function() {
	var tags = $("[xdiv]");
	var i = 1;
	$(tags).each(function(index, element) {
		$(element).css("z-index", i);
		i--;
		$(element).addClass("viewport");
		var url = $(element).attr("xdiv"); //获取url
		var pageName = $(element).attr("page-name"); //获取page-name
		pageNameArray.push(pageName); //将page加入到数据
		$.data(pageCache, pageName, element); //JQ缓存
		$.get(url, function(data, status) {
			if (status == 'success') {
				$(element).html(data);
			}
		});

	});
});

/**
 * 页面跳转
 * @param {Object} fromName
 * @param {Object} toName
 * @param {Object} outAnimation
 * @param {Object} inAnimation
 * @param {Object} delay
 */
function toPage(fromName, toName, outAnimation, inAnimation, delay) {
	var fromElement = $.data(pageCache, fromName); //读取缓存
	var toElement = $.data(pageCache, toName); //读取缓存
	adjustPageIndex(fromName, toName); //调整页面index
	$(fromElement).addClass("animated " + outAnimation);
	setTimeout(function(){
		$(toElement).css('display', 'block');
		$(toElement).addClass("animated " + inAnimation);
	}, delay);
	//动画结束事件
	setTimeout(function(){
		$(toElement).css("z-index", 1); //跳转页放到第一*/
		console.log(fromElement);
		$(fromElement).css('display', 'none');
		$(fromElement).removeClass("animated " + outAnimation);
		$(toElement).removeClass("animated " + inAnimation);
		adjustPageIndex(toName, fromName);
	}, 1000);
	
	/*$(fromElement).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
		
	});*/
}

/**
 * 调整页面index
 * @param {Object} toName 要跳转到的pageName
 */
function adjustPageIndex(fromName, toName) {
	$(pageNameArray).each(function(index, pageName) {
		var pageElement = $.data(pageCache, pageName);
		if (pageName == fromName) {
			//如果是当前页则不操作
		} else if (pageName == toName) {
			$(pageElement).css('z-index', 0); //是目标页则放到当前页下一层
			$(pageElement).css('display', 'none');
		} else {
			$(pageElement).css('display', 'none');
			$(pageElement).css('z-index', -1); //其他页放在目标页后面
		}
	});
}